<?php

namespace app\admin\model\outhouse;

use app\admin\model\information\Shelves;
use app\admin\model\information\Warehouse;
use think\Db;
use think\Model;
use traits\model\SoftDelete;

class Rdinrecord extends Model
{

    use SoftDelete;

    

    // 表名
    protected $name = 'rdinrecord';
    
    // 自动写入时间戳字段
   // protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';


    public function wareHouse(){
        return $this->hasOne('\app\admin\model\information\Warehouse','id','warehouse_id')->field('id,name');
    }
    public function changeWareHouse(){
        return $this->hasOne('\app\admin\model\information\Warehouse','id','warehouse_change_id')->field('id,name');
    }

    public function shelves(){
        return $this->hasOne('\app\common\model\Shelves','id','shelves_id')->field('id,name');
    }

    public function changeShelves(){
        return $this->hasOne('\app\common\model\Shelves','id','shelves_change_id')->field('id,name');
    }


    public function insertMiddlData($data,$type = 'in',$k)
    {
        if ($type == 'in') {
            $table  = 'RdRecord08';
            $tables = 'rdrecords08';
        } elseif ($type == 'out') {
            $table  = 'RdRecord09';
            $tables = 'rdrecords09';
        }
        //插入中间库

        
        
        $id =  Db::connect('database.inc')->table($table)->where('cCode',$data['code'])->value('ID');
        if(empty($id)){
            $id = time();
            Db::connect('database.inc')->table($table)->insertGetId([
                'bRdFlag'=>1,
                'cVouchType' =>$type=='in'?'08':'09',
                'cSource' => '库存',
                'cWhCode' => $data['wh_code'],
                'dDate'=>$data['code_date'],
                'cCode'=>$data['code'],
                'bIsSTQc'=>1,
                'bTransFlag'=>1,
                'ID'=>$id,
            ]);
        }
        //$currentTime = microtime(true);
        //$milliseconds = round($currentTime * 1000);
        
        $check_AutoID = Db::connect('database.inc')->table($tables)->where([
            'irowno' => $data['row_id'],
            'ID' => $id
        ])->value('AutoID');
        if($check_AutoID){
            exception("单号{$data['code']}已存在中间表，请核实");
        }
        
        Db::connect('database.inc')->table($tables)->insert([
            'cInvCode'=>$data['cInvCode'],
            'ID' => $id,//表头单号
            //'AutoID'=>time()+$k,//自增
            'irowno' => $data['row_id'],//行号
            'iQuantity' => $data['iQuantity'],
            'iFlag' => 0
        ]);
    }
}
